package com.powernode.settings.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.powernode.commons.utils.ResponseData;
import com.powernode.settings.bean.DicTypeBean;
import com.powernode.settings.bean.DicValueBean;
import com.powernode.settings.dao.DicTypeMapper;
import com.powernode.settings.dao.DicValueMapper;
import com.powernode.settings.service.DicTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DicTypeServiceImpl implements DicTypeService {
    @Autowired
    private DicTypeMapper dao;
    @Autowired
    private DicValueMapper dicValueMapper;

    /**
     * 查询所有 并分页
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResponseData findAll(Integer pageNum, Integer pageSize) {
        Page<DicTypeBean> page = PageHelper.startPage(pageNum, pageSize);
        dao.selectAll();
        return ResponseData.ok(page.getResult(),page.getTotal());
    }

    /**
     * 插入字典类型
     * 注意:先判断字典类型的code是否已经存在,如果存在不让插入
     * @param type
     * @return
     */
    @Override
    public ResponseData addType(DicTypeBean type) {
        DicTypeBean dicType = dao.selectByPrimaryKey(type.getCode());
        if (null!=dicType){//主键已经存在
            return ResponseData.error("字典类型的code已经存在");
        }
        int row = dao.insertSelective(type);
        if (row>0){
            return ResponseData.ok();
        }
        return ResponseData.error();
    }

    /**
     * 根据主键code修改字典类型
     * @param type
     * @return
     */
    @Override
    public ResponseData modifyTypeByCode(DicTypeBean type) {
        int row = dao.updateByPrimaryKeySelective(type);
        if (row>0){
            return  ResponseData.ok();
        }
        return ResponseData.error();
    }

    /**
     * 根据主键删除
     * 注意:查询看字典类型有没有正在被字典值使用
     * @param codes  1,2,3,43,4  ====>[1,2,3,4,5]
     * @return
     */
    @Override
    public ResponseData removeTypeByCodes(String codes) {
        //字典类型的主键
        String[] codeArr = codes.split(",");
        //查询看字典类型有没有正在被字典值使用
        List<DicValueBean> dicValue = dicValueMapper.selectBatchByCode(codeArr);
        if (dicValue.size()>0){
            return ResponseData.error("字典类型正在被使用");
        }
        int row = dao.deleteBatch(codeArr);
        if (row>0){
            return ResponseData.ok();
        }
        return ResponseData.error();
    }


}
